<?php

declare (strict_types=1);

namespace app\common\service;

use app\common\exception\AdminException;
use app\common\repository\order\OrderRepository;
use Psr\Http\Message\ResponseInterface;
use Yansongda\Artful\Exception\ContainerException;
use Yansongda\Artful\Exception\InvalidParamsException;
use Yansongda\Artful\Rocket;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Provider\Alipay;
use Yansongda\Pay\Provider\Wechat;
use Yansongda\Supports\Collection;

class PayService
{
    protected mixed $config;

    public function __construct()
    {
        $this->config = config('pay');
    }

    /**
     * 订单收银台
     *
     * @param $order_id
     * @return \app\common\model\BaseModel|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkout($order_id): ?\app\common\model\BaseModel
    {
        $orderRep = app()->make(OrderRepository::class);
        $orderInfo = $orderRep->getOne($order_id);
        if($orderInfo->payment_status !== 0) {
            throw new AdminException('订单不存在或已支付');
        }
        return $orderInfo;
    }

    /**
     * 获取支付实例
     *
     * @param $platform
     * @return Alipay|Wechat
     */
    public function getInstance($platform = null): Alipay|Wechat
    {
        $platform = strtolower($platform);

        $config = $this->config[$platform] ?? null;

        if (!$config) {
            throw new AdminException("未配置的支付渠道: {$platform}");
        }

        try {
            Pay::config($this->config);
        } catch (ContainerException $e) {
            throw new AdminException("初始化失败:" . $e->getMessage());
        }

        return match ($platform) {
            'alipay' => Pay::alipay($config),
            'wechat' => Pay::wechat($config),
            default => throw new AdminException("未配置的支付渠道: {$platform}"),
        };
    }

    /**
     * 发起支付
     *
     * @param string $platform 支付平台 alipay|wechat
     * @param array $orderData 订单数据
     * @return ResponseInterface|Rocket|Collection
     */
    public function createOrder(string $platform, array $orderData): Collection|ResponseInterface|Rocket
    {
        $instance = $this->getInstance($platform);

        return match ($platform) {
            'alipay', 'wechat' => $instance->app($orderData),
            default => throw new AdminException("未配置的支付渠道: {$platform}"),
        };
    }

    /**
     * 支付回调
     *
     * @param string $platform 支付平台
     * @return Rocket|Collection
     * @throws ContainerException
     * @throws InvalidParamsException
     */
    // 处理回调
    public function handleNotify(string $platform): Collection|Rocket
    {
        $instance = $this->getInstance($platform);
        return $instance->callback();
    }
}